#include "bsp/bsp.h"
#include "at32f413_clock.h"
#include "gpio.h"
#include "version.h"
#include "utils/logger.h"

static void wdog_init(void);

static void system_init(void) {
	system_clock_config();
	nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
	SysTick_Config(SystemCoreClock / 1000);
	crm_periph_clock_enable(CRM_IOMUX_PERIPH_CLOCK, TRUE);
	wdog_init();
}

static void board_init(void) {
	cpu_ticks_enable();
}

void bsp_init(void) {
	system_init();
	board_init();
}

u8 mcu_chip_id(u8 *buff)
{
	u32 values[] = { REG32(0x1FFFF7E8), REG32(0x1FFFF7EC), REG32(0x1FFFF7F0)};
	memcpy(buff, values, sizeof(values));
	return sizeof(values);
}

u32 mcu_flash_capicity(void) {
	u32 Kbytes = REG32(0x1FFFF7E0) & 0xFFFF;
	return (Kbytes << 10);
}

static void wdog_init(void)
{
#if (CONFIG_DEBUG==0)
	/* disable register write protection */
	 wdt_register_write_enable(TRUE);
	
	 /* set the wdt divider value */
	 wdt_divider_set(WDT_CLK_DIV_64);
	
	 /* set reload value
	
	  timeout = reload_value * (divider / lick_freq )	 (s)
	
	  lick_freq    = 40000 Hz
	  divider	   = 4
	  reload_value = 30000
	
	  timeout = 3000 * (64 / 40000 ) = 4.8s = 4800ms
	 */
	 wdt_reload_value_set(3000 - 1);
	
	 /* reload wdt counter */
	 wdt_counter_reload();
	 
	 /* enable wdt */
	 wdt_enable();
#endif
}

void wdog_reload(void) {
#if (CONFIG_DEBUG==0)
	wdt_counter_reload();
#endif
}
